﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace AutoCode.SqlServer
{
    /// <summary>
    ///DBHelper 的摘要说明
    /// </summary>
    public class DBHelper
    {
        //SqlConnection
        public static SqlConnection Conn
        {
            get
            {
                return new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["conStr"]);
            }
        }

        //select
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="par"></param>
        /// <returns></returns>
        public static SqlDataReader GetAllBySql(string sql, params SqlParameter[] par)
        {
            SqlCommand cmd = new SqlCommand(sql, Conn);
            cmd.Parameters.AddRange(par);
            cmd.Connection.Open();
            try
            {
                return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            }
            catch
            {
                cmd.Connection.Close();
                return null;
            }
        }

        //insert,update,delete
        /// <summary>
        /// 实现增加、修改、删除
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="par"></param>
        /// <returns></returns>
        public static int ExeNonQuery(string sql, params SqlParameter[] par)
        {
            int r = -1;
            SqlCommand cmd = new SqlCommand(sql, Conn);
            cmd.Parameters.AddRange(par);
            cmd.Connection.Open();
            try
            {
                r = cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                cmd.Connection.Close();
            }
            return r;
        }

        //get table
        public static DataTable GetTableBySql(string sql)
        {
            SqlDataAdapter da = new SqlDataAdapter(sql, Conn);
            DataTable tab = new DataTable();
            da.Fill(tab);
            return tab;
        }
        /// <summary>
        /// get table
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="sp"></param>
        /// <returns></returns>
        public static DataTable SpGetTableBySql(string sql, params SqlParameter[] sp)
        {
            SqlCommand cmd = new SqlCommand(sql, Conn);
            cmd.Parameters.AddRange(sp);
            cmd.Connection.Open();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            try
            {
                return dt;
            }
            catch
            {
                cmd.Connection.Close();
                return null; ;
            }
        }
    }
}